package com.tticar.invmanager.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tticar.invmanager.common.Enum.CodeType;
import com.tticar.invmanager.common.exception.MyServiceException;
import com.tticar.invmanager.common.shiro.LoginUser;
import com.tticar.invmanager.common.shiro.MySecurityUtils;
import com.tticar.invmanager.common.utils.ServiceUtil;
import com.tticar.invmanager.entity.MMateriel;
import com.tticar.invmanager.entity.OutRepositoryDetail;
import com.tticar.invmanager.entity.RepositoryCount;
import com.tticar.invmanager.entity.vo.*;
import com.tticar.invmanager.mapper.MMaterielTticarMapper;
import com.tticar.invmanager.mapper.OutRepositoryDetailMapper;
import com.tticar.invmanager.service.ICodeCounterService;
import com.tticar.invmanager.service.IInRepositoryDetailService;
import com.tticar.invmanager.service.IOutRepositoryDetailService;
import com.tticar.invmanager.service.IRepositoryCountService;
import com.tticar.invmanager.tticar.entity.DeliveryGoodsDTO;
import com.tticar.invmanager.tticar.entity.GoodsOrder;
import com.tticar.invmanager.tticar.service.IGoodsOrderService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 出库单详情 服务实现类
 * </p>
 *
 * @author joeyYan
 * @since 2018-08-06
 */
@Service("outRepositoryDetailService")
public class OutRepositoryDetailServiceImpl extends ServiceImpl<OutRepositoryDetailMapper, OutRepositoryDetail> implements IOutRepositoryDetailService {

    @Autowired
    private ICodeCounterService codeCounterService;

    @Autowired
    private IRepositoryCountService repositoryCountService;

    @Autowired
    private IGoodsOrderService goodsOrderService;
    @Autowired
    private MMaterielTticarMapper mMaterielTticarMapper;
    @Autowired
    private IInRepositoryDetailService inRepositoryDetailService;

    @Override
    public Page selectPage(OutRepositoryDetailSearchDto searchDto, MyPage<OutRepositoryDetail> page) {
        return page.setRecords(baseMapper.search(searchDto, page));
    }


    @Override
    public List<Map> getDetailByCode(String code) {
        return this.baseMapper.getDetailByCode(code);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> ids) {
        List list = new ArrayList();
        for (Long id : ids) {
            OutRepositoryDetail outRepositoryDetail = new OutRepositoryDetail();
            outRepositoryDetail.setId(id);
            //删除为-1，区分删除和禁用
            outRepositoryDetail.setStatus(-1);
            list.add(outRepositoryDetail);
        }
        this.updateBatchById(list);
    }

    /**
     * 新增出库单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOutRepositoryDetail(OutRepositoryDetailAddDTO dto) {
        //获取当前操作人
        Subject subject = SecurityUtils.getSubject();
        LoginUser loginUser = (LoginUser) subject.getPrincipal();
        String username = loginUser.getUsername();

        List<InRepositoryGoodsDTO> inRepositoryGoodsDTOs = dto.getInRepositoryGoodsDTOs();
        String code = codeCounterService.getOrderCode(CodeType.CK);
        for (int i = 0; i < inRepositoryGoodsDTOs.size(); i++) {
            OutRepositoryDetail outRepositoryDetail = new OutRepositoryDetail();
            //批量插入记录的公共数据
            outRepositoryDetail.setType(dto.getOutRepositoryType());
            outRepositoryDetail.setOrderTime(dto.getOrderTime());
            outRepositoryDetail.setCode(code);
            outRepositoryDetail.setUsername(username);
            //批量插入记录的各自数据
            String house = inRepositoryGoodsDTOs.get(i).getHouse();
            Long positionId = inRepositoryGoodsDTOs.get(i).getPositionId();
            Long wearhouseId = inRepositoryGoodsDTOs.get(i).getWearhouseId();
            if (StringUtils.isNotBlank(house)) {
                String[] split = house.split("_");
                positionId = Long.parseLong(split[0]);
                wearhouseId = Long.parseLong(split[2]);
            }
            outRepositoryDetail.setBatchNumber(inRepositoryGoodsDTOs.get(i).getBatchCode());
            outRepositoryDetail.setSkuId(inRepositoryGoodsDTOs.get(i).getSkusId());
            outRepositoryDetail.setPositionId(positionId);
            outRepositoryDetail.setWearhouseId(wearhouseId);
            outRepositoryDetail.setProviderId(inRepositoryGoodsDTOs.get(i).getRalativeId());
            outRepositoryDetail.setCount(inRepositoryGoodsDTOs.get(i).getCount());
            outRepositoryDetail.setRemark(inRepositoryGoodsDTOs.get(i).getRemark());
            //减少库存量
//            RepositoryCount repositoryCount =
//                    repositoryCountService.selectDataBySkuIdAndWearhouseId(inRepositoryGoodsDTOs.get(i).getSkusId(), inRepositoryGoodsDTOs.get(i).getWearhouseId());
//            if (repositoryCount == null || repositoryCount.getCount() - inRepositoryGoodsDTOs.get(i).getCount() < 1) {
//                throw new MyServiceException("库存不足");
//            }else {
//                repositoryCount.setCount(repositoryCount.getCount() - inRepositoryGoodsDTOs.get(i).getCount());
//                repositoryCountService.updateById(repositoryCount);
//            }
            Integer count = -inRepositoryGoodsDTOs.get(i).getCount();
            repositoryCountService.updateRepositoryCount(inRepositoryGoodsDTOs.get(i).getSkusId(), wearhouseId, count);

            insertOrUpdate(outRepositoryDetail);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deliveryGoods(List<DeliveryGoodsDTO> deliveryGoodsDTOs,Long id) {
        String ckCode = codeCounterService.getOrderCode(CodeType.CK);
        for (DeliveryGoodsDTO deliveryGoodsCircle : deliveryGoodsDTOs) {
            String house = deliveryGoodsCircle.getHouse();
            if (StringUtils.isBlank(house)) {
                //伪出库cxymark
//                Map mMateriel = mMaterielTticarMapper.queryDefaultHouse(deliveryGoodsCircle.getSkuId());
//                house = mMateriel.get("houseId") +"_默认仓库_" + mMateriel.get("positionId")+"_默认库位_" + "SYSTEM00000_" + deliveryGoodsCircle.getInvNeedCount() + "_"+ deliveryGoodsCircle.getInvNeedCount();
               // throw new MyServiceException("货物库存不足");
//                return;

            }
//            String[] arr = house.split(",");
            List<RepositoryCount> repositoryCounts = repositoryCountService.queryOutRepository(deliveryGoodsCircle.getSkuId());
            Integer totalHasNum = 0;
            if (repositoryCounts != null && repositoryCounts.size() > 0) {

                Integer count = deliveryGoodsCircle.getInvNeedCount();


            for (RepositoryCount rep : repositoryCounts) {

                Long wearhouseId = rep.getWearhouseId();

                Integer num = Integer.valueOf(rep.getCount() > count?count:rep.getCount());
                totalHasNum += num;

                OutRepositoryDetail outDetail = new OutRepositoryDetail();
                outDetail.setSkuId(deliveryGoodsCircle.getSkuId());
                outDetail.setCode(ckCode);
                outDetail.setBuszId(id);
                outDetail.setWearhouseId(wearhouseId);
                outDetail.setType(4);
                outDetail.setCount(num);
                outDetail.setStatus(0);
                outDetail.setCtime(new Date());
                outDetail.setOrderTime(new Date());
                outDetail.setRemark("天天爱车平台:订单发货出库。");
                outDetail.setUsername(MySecurityUtils.currentUser().getUsername());
                //生成出库单
                insertOrUpdate(outDetail);
                //更新库存
                repositoryCountService.updateRepositoryCount(deliveryGoodsCircle.getSkuId(), wearhouseId, num * -1);
                if (totalHasNum > count) {
                    break;
                }
            }
            }
            //不够要补发 伪造出库  new version 改为不可发货
            if (totalHasNum < deliveryGoodsCircle.getInvNeedCount()) {
                throw new MyServiceException("货物库存不足");
//                int lackNum = deliveryGoodsCircle.getInvNeedCount() - totalHasNum;
//                Map mMateriel = mMaterielTticarMapper.queryDefaultHouse(deliveryGoodsCircle.getSkuId());
//                house = mMateriel.get("houseId") +"_默认仓库_" + mMateriel.get("positionId")+"_默认库位_" + "SYSTEM00000_" + lackNum + "_"+ lackNum;
//                String[] arr1 = house.split(",");
//                String[] lackArr = arr1[0].split("_");
//                Long wearhouseId = Long.valueOf(lackArr[0]);
//                Long positionId = Long.valueOf(lackArr[2]);
//                String batchCode = lackArr[4];
//                Integer num = Integer.valueOf(lackArr[6]);
//                OutRepositoryDetail outDetail = new OutRepositoryDetail();
//                outDetail.setSkuId(deliveryGoodsCircle.getSkuId());
//                outDetail.setCode(ckCode);
//                outDetail.setBuszId(id);
//                outDetail.setBatchNumber(batchCode);
//                outDetail.setWearhouseId(wearhouseId);
//                outDetail.setPositionId(positionId);
//                outDetail.setType(0);
//                outDetail.setCount(num);
//                outDetail.setStatus(0);
//                outDetail.setCtime(new Date());
//                outDetail.setOrderTime(new Date());
//                outDetail.setRemark("天天爱车平台:订单发货出库。");
//                outDetail.setUsername("admin");
//
//                //生成出库单
//                insertOrUpdate(outDetail);
//                //更新库存
//                repositoryCountService.updateRepositoryCountByPositionIdAndTenantId(deliveryGoodsCircle.getSkuId(), wearhouseId, positionId, num * -1, MySecurityUtils.currentUser().getTenantId());



            }

        }
    }
    /**
     * 员工端发货 扣除仓储库存
     */
//    @Override
//    @Async
//    public void deliveryGoodsByStaffClient(String goodsOrderId) {
//        if (StringUtils.isBlank(goodsOrderId)) {
//            throw new MyServiceException("参数订单号不能为空");
//        }
//        //查询该笔订单下 有几个sku
//        List<SkuReturnToPage> skuReturnToPages = goodsOrderService.queryGoodsDetailByOrderId(Long.valueOf(goodsOrderId));
//        if (skuReturnToPages != null && skuReturnToPages.size() > 0) {
//            for (SkuReturnToPage skus : skuReturnToPages) {
//                Long aLong = mMaterielTticarMapper.queryRelativeInvMaterielId(skus.getGoodsId(), skus.getSkuValue());
//                //如果未关联存货，跳出
//                if (aLong == null) {
//                    break;
//                }
//               //如果关联了 查询默认出库
//                String house = inRepositoryDetailService.getSkuHouseByNum(aLong, skus.getCount(), null);
//                //进行出库
//                String ckCode = codeCounterService.getOrderCode(CodeType.CK);
//                String[] arr = house.split(",");
//                for (int i = 0; i < arr.length; i++) {
//                    String[] arr2 = arr[i].split("_");
//                    Long wearhouseId = Long.valueOf(arr2[0]);
//                    Long positionId = Long.valueOf(arr2[2]);
//                    String batchCode = arr2[4];
//                    Integer num = Integer.valueOf(arr2[6]);
//
//                    OutRepositoryDetail outDetail = new OutRepositoryDetail();
//                    outDetail.setSkuId(aLong);
//                    outDetail.setCode(ckCode);
//                    outDetail.setBuszId(Long.valueOf(goodsOrderId));
//                    outDetail.setBatchNumber(batchCode);
//                    outDetail.setWearhouseId(wearhouseId);
//                    outDetail.setPositionId(positionId);
//                    outDetail.setType(0);
//                    outDetail.setCount(num);
//                    outDetail.setStatus(0);
//                    outDetail.setCtime(new Date());
//                    outDetail.setOrderTime(new Date());
//                    outDetail.setRemark("天天爱车平台:订单发货出库。");
//                    outDetail.setUsername(MySecurityUtils.currentUser().getUsername());
//                    //生成出库单
//                    insertOrUpdate(outDetail);
//                    //更新库存
//                    repositoryCountService.updateRepositoryCountByPositionId(aLong, wearhouseId, positionId, num * -1);
//                }
//
//            }
//        }
//
//
//    }
}
